from flask import Flask, jsonify, request, send_file
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import os
from datetime import datetime
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from models.base import db
from models import Employee, Project, WorkExperience, Certificate, ResumeTemplate, Contract, ContractAttachment, ResumeAttachment, CertificateAttachment, CertificateName
from routes import (
    employee_bp,
    work_experience_bp,
    project_bp,
    certificate_bp,
    template_bp,
    contract_bp,
    attachment_bp,
    training_bp,
    certificate_name_bp,
    export_bp,
    init_bp,
    education_bp,
    reward_punishment_bp,
    dict_bp
)

app = Flask(__name__)
CORS(app)

# 配置数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///employee.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

# 注册蓝图
app.register_blueprint(employee_bp)
app.register_blueprint(work_experience_bp)
app.register_blueprint(project_bp)
app.register_blueprint(certificate_bp)
app.register_blueprint(template_bp)
app.register_blueprint(contract_bp)
app.register_blueprint(attachment_bp)
app.register_blueprint(training_bp)
app.register_blueprint(certificate_name_bp)
app.register_blueprint(export_bp)
app.register_blueprint(init_bp)
app.register_blueprint(education_bp)
app.register_blueprint(reward_punishment_bp)
app.register_blueprint(dict_bp)

# 创建数据库表（如果不存在）
with app.app_context():
    # 检查数据库文件是否存在
    db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'employee.db')
    if not os.path.exists(db_path):
        db.create_all()
        # 初始化示例数据
        from init_db import init_db
        init_db(app, db)

# API路由
@app.route('/api/employees', methods=['GET'])
def get_employees():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    # 获取分页数据
    employees = Employee.query.paginate(page=page, per_page=per_page, error_out=False)
    
    return jsonify({
        'total': employees.total,
        'page': page,
        'per_page': per_page,
        'total_pages': employees.pages,
        'data': [employee.to_dict() for employee in employees.items]
    })

@app.route('/api/employees', methods=['POST'])
def create_employee():
    data = request.get_json()
    employee = Employee(**data)
    db.session.add(employee)
    db.session.commit()
    return jsonify({'message': 'Employee created successfully', 'id': employee.id}), 201

@app.route('/api/employees/<int:id>', methods=['PUT'])
def update_employee(id):
    employee = Employee.query.get_or_404(id)
    data = request.get_json()
    for key, value in data.items():
        setattr(employee, key, value)
    db.session.commit()
    return jsonify({'message': 'Employee updated successfully'})

@app.route('/api/employees/<int:id>', methods=['DELETE'])
def delete_employee(id):
    employee = Employee.query.get_or_404(id)
    db.session.delete(employee)
    db.session.commit()
    return jsonify({'message': 'Employee deleted successfully'})

@app.route('/api/employees/<int:id>', methods=['GET'])
def get_employee(id):
    employee = Employee.query.get_or_404(id)
    return jsonify(employee.to_dict())

# 证书相关API
@app.route('/api/employees/<int:employee_id>/certificates', methods=['GET'])
def get_employee_certificates(employee_id):
    certificates = Certificate.query.filter_by(employee_id=employee_id).all()
    return jsonify([certificate.to_dict() for certificate in certificates])

@app.route('/api/employees/<int:employee_id>/certificates', methods=['POST'])
def create_employee_certificate(employee_id):
    data = request.get_json()
    data['employee_id'] = employee_id
    certificate = Certificate(**data)
    db.session.add(certificate)
    db.session.commit()
    return jsonify({'message': 'Certificate created successfully', 'id': certificate.id}), 201

@app.route('/api/employees/<int:employee_id>/certificates/<int:id>', methods=['PUT'])
def update_employee_certificate(employee_id, id):
    certificate = Certificate.query.filter_by(id=id, employee_id=employee_id).first_or_404()
    data = request.get_json()
    for key, value in data.items():
        setattr(certificate, key, value)
    db.session.commit()
    return jsonify({'message': 'Certificate updated successfully'})

@app.route('/api/employees/<int:employee_id>/certificates/<int:id>', methods=['DELETE'])
def delete_employee_certificate(employee_id, id):
    certificate = Certificate.query.filter_by(id=id, employee_id=employee_id).first_or_404()
    db.session.delete(certificate)
    db.session.commit()
    return jsonify({'message': 'Certificate deleted successfully'})

# 项目经验相关API
@app.route('/api/employees/<int:employee_id>/projects', methods=['GET'])
def get_projects(employee_id):
    projects = Project.query.filter_by(employee_id=employee_id).order_by(Project.start_date.desc()).all()
    return jsonify([project.to_dict() for project in projects])

@app.route('/api/employees/<int:employee_id>/projects', methods=['POST'])
def create_project(employee_id):
    data = request.get_json()
    data['employee_id'] = employee_id
    project = Project(**data)
    db.session.add(project)
    db.session.commit()
    return jsonify({'message': 'Project created successfully', 'id': project.id}), 201

@app.route('/api/employees/<int:employee_id>/projects/<int:id>', methods=['PUT'])
def update_project(employee_id, id):
    project = Project.query.filter_by(id=id, employee_id=employee_id).first_or_404()
    data = request.get_json()
    for key, value in data.items():
        setattr(project, key, value)
    db.session.commit()
    return jsonify({'message': 'Project updated successfully'})

@app.route('/api/employees/<int:employee_id>/projects/<int:id>', methods=['DELETE'])
def delete_project(employee_id, id):
    project = Project.query.filter_by(id=id, employee_id=employee_id).first_or_404()
    db.session.delete(project)
    db.session.commit()
    return jsonify({'message': 'Project deleted successfully'})

# 工作经历相关API
@app.route('/api/employees/<int:employee_id>/work_experiences', methods=['GET'])
def get_work_experiences(employee_id):
    work_experiences = WorkExperience.query.filter_by(employee_id=employee_id).order_by(WorkExperience.start_date.desc()).all()
    return jsonify([work_experience.to_dict() for work_experience in work_experiences])

@app.route('/api/employees/<int:employee_id>/work_experiences', methods=['POST'])
def create_work_experience(employee_id):
    data = request.get_json()
    data['employee_id'] = employee_id
    experience = WorkExperience(**data)
    db.session.add(experience)
    db.session.commit()
    return jsonify({'message': 'Work experience created successfully', 'id': experience.id}), 201

@app.route('/api/employees/<int:employee_id>/work_experiences/<int:id>', methods=['PUT'])
def update_work_experience(employee_id, id):
    experience = WorkExperience.query.filter_by(id=id, employee_id=employee_id).first_or_404()
    data = request.get_json()
    for key, value in data.items():
        setattr(experience, key, value)
    db.session.commit()
    return jsonify({'message': 'Work experience updated successfully'})

@app.route('/api/employees/<int:employee_id>/work_experiences/<int:id>', methods=['DELETE'])
def delete_work_experience(employee_id, id):
    experience = WorkExperience.query.filter_by(id=id, employee_id=employee_id).first_or_404()
    db.session.delete(experience)
    db.session.commit()
    return jsonify({'message': 'Work experience deleted successfully'})

# 简历模板相关API
@app.route('/api/templates', methods=['GET'])
def get_templates():
    templates = ResumeTemplate.query.all()
    return jsonify([template.to_dict() for template in templates])

@app.route('/api/templates', methods=['POST'])
def create_template():
    data = request.get_json()
    template = ResumeTemplate(**data)
    db.session.add(template)
    db.session.commit()
    return jsonify({'message': 'Template created successfully', 'id': template.id}), 201

@app.route('/api/templates/<int:id>', methods=['PUT'])
def update_template(id):
    template = ResumeTemplate.query.get_or_404(id)
    data = request.get_json()
    for key, value in data.items():
        setattr(template, key, value)
    db.session.commit()
    return jsonify({'message': 'Template updated successfully'})

@app.route('/api/templates/<int:id>', methods=['DELETE'])
def delete_template(id):
    template = ResumeTemplate.query.get_or_404(id)
    db.session.delete(template)
    db.session.commit()
    return jsonify({'message': 'Template deleted successfully'})

@app.route('/api/templates/<int:id>/set-default', methods=['PUT'])
def set_default_template(id):
    # 清除所有模板的默认状态
    ResumeTemplate.query.update({'is_default': False})
    # 设置新的默认模板
    template = ResumeTemplate.query.get_or_404(id)
    template.is_default = True
    db.session.commit()
    return jsonify({'message': 'Default template set successfully'})

@app.route('/api/employees/<int:employee_id>/export/<int:template_id>', methods=['GET'])
def export_resume(employee_id, template_id):
    try:
        # 获取员工信息
        employee = Employee.query.get(employee_id)
        if not employee:
            return jsonify({'error': '员工不存在'}), 404

        # 获取模板
        template = ResumeTemplate.query.get(template_id)
        if not template:
            return jsonify({'error': '模板不存在'}), 404

        # 创建Word文档
        doc = Document()
        
        # 添加标题
        title = doc.add_heading(f'{employee.name}的简历', 0)
        title.alignment = WD_ALIGN_PARAGRAPH.CENTER

        # 基本信息
        doc.add_heading('基本信息', level=1)
        basic_info = doc.add_paragraph()
        basic_info.add_run(f'姓名：{employee.name}\n')
        basic_info.add_run(f'性别：{employee.gender}\n')
        basic_info.add_run(f'出生日期：{employee.birth_date}\n')
        basic_info.add_run(f'联系电话：{employee.phone}\n')
        basic_info.add_run(f'邮箱：{employee.email}\n')
        basic_info.add_run(f'毕业院校：{employee.school}\n')
        basic_info.add_run(f'学历：{employee.degree}\n')

        # 工作经历
        if employee.work_experiences:
            doc.add_heading('工作经历', level=1)
            for exp in employee.work_experiences:
                exp_para = doc.add_paragraph()
                exp_para.add_run(f'{exp.company} | {exp.position}\n')
                exp_para.add_run(f'{exp.start_date} - {exp.end_date}\n')
                exp_para.add_run(f'部门：{exp.description}\n')
                exp_para.add_run(f'主要职责：{exp.responsibilities}\n')
                exp_para.add_run(f'工作成果：{exp.achievements}\n')

        # 项目经验
        if employee.projects:
            doc.add_heading('项目经验', level=1)
            for project in employee.projects:
                project_para = doc.add_paragraph()
                project_para.add_run(f'{project.name} | {project.client_name} | {project.role}\n')
                project_para.add_run(f'{project.start_date} - {project.end_date}\n')
                project_para.add_run(f'项目描述：{project.description}\n')
                project_para.add_run(f'主要职责：{project.responsibilities}\n')
                project_para.add_run(f'项目成果：{project.achievements}\n')

        # 技能证书
        if employee.skills:
            doc.add_heading('技能证书', level=1)
            skill_para = doc.add_paragraph()
            skill_para.add_run(employee.skills)

        # 保存文档
        filename = f'resume_{employee.name}.docx'
        doc.save(filename)

        # 发送文件
        return send_file(
            filename,
            as_attachment=True,
            download_name=filename,
            mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        )

    except Exception as e:
        return jsonify({'error': str(e)}), 500
    finally:
        # 删除临时文件
        if os.path.exists(filename):
            os.remove(filename)

# 合同管理相关API
@app.route('/api/contracts', methods=['GET'])
def get_contracts():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    employee_name = request.args.get('employee_name', '')
    status = request.args.get('status', None)
    
    # 构建查询
    query = Contract.query.join(Employee)
    
    # 按员工姓名筛选
    if employee_name:
        query = query.filter(Employee.name.ilike(f'%{employee_name}%'))
    
    # 按合同状态筛选
    if status:
        is_expired = status == 'expired'
        query = query.filter(Contract.is_expired == is_expired)
    
    # 更新所有合同状态
    current_time = datetime.now()
    contracts_to_update = Contract.query.filter_by(is_expired=False).all()
    for contract in contracts_to_update:
        if current_time > contract.end_date:
            contract.is_expired = True
            contract.updated_at = current_time
    db.session.commit()
    
    # 按签订时间倒序排序
    query = query.order_by(Contract.start_date.desc())
    
    # 分页
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)
    
    return jsonify({
        'total': pagination.total,
        'page': page,
        'per_page': per_page,
        'total_pages': pagination.pages,
        'items': [
            {
                **contract.to_dict(),
                'employee_name': contract.employee.name,
                'phone': contract.employee.phone
            }
            for contract in pagination.items
        ]
    })

@app.route('/api/contracts', methods=['POST'])
def create_contract():
    data = request.get_json()
    
    # 检查员工是否存在
    employee = Employee.query.get(data['employee_id'])
    if not employee:
        return jsonify({'error': 'Employee not found'}), 404
    
    # 创建合同记录
    contract = Contract(
        employee_id=data['employee_id'],
        contract_number=data['contract_number'],
        contract_type=data['contract_type'],
        contract_party=data['contract_party'],
        start_date=datetime.fromisoformat(data['start_date'].split('T')[0]),
        end_date=datetime.fromisoformat(data['end_date'].split('T')[0]),
        is_expired=datetime.now() > datetime.fromisoformat(data['end_date'].split('T')[0])
    )
    
    db.session.add(contract)
    db.session.commit()
    
    return jsonify({
        'message': 'Contract created successfully',
        'id': contract.id
    }), 201

@app.route('/api/contracts/<int:id>', methods=['PUT'])
def update_contract(id):
    contract = Contract.query.get_or_404(id)
    data = request.get_json()
    
    # 检查员工是否存在
    employee = Employee.query.get(data['employee_id'])
    if not employee:
        return jsonify({'error': 'Employee not found'}), 404
    
    # 更新合同信息
    contract.employee_id = data['employee_id']
    contract.contract_number = data['contract_number']
    contract.contract_type = data['contract_type']
    contract.contract_party = data['contract_party']
    contract.start_date = datetime.fromisoformat(data['start_date'].split('T')[0])
    contract.end_date = datetime.fromisoformat(data['end_date'].split('T')[0])
    contract.is_expired = datetime.now() > datetime.fromisoformat(data['end_date'].split('T')[0])
    contract.updated_at = datetime.now()
    
    db.session.commit()
    
    return jsonify({'message': 'Contract updated successfully'})

@app.route('/api/contracts/<int:id>', methods=['DELETE'])
def delete_contract(id):
    contract = Contract.query.get_or_404(id)
    db.session.delete(contract)
    db.session.commit()
    return jsonify({'message': 'Contract deleted successfully'})

@app.route('/api/employees/search', methods=['GET'])
def search_employees():
    query = request.args.get('query', '')
    employees = Employee.query.filter(Employee.name.ilike(f'%{query}%')).all()
    return jsonify([{'id': emp.id, 'name': emp.name} for emp in employees])

# 合同附件相关API
@app.route('/api/contracts/<int:contract_id>/attachments', methods=['GET'])
def get_attachments(contract_id):
    attachments = ContractAttachment.query.filter_by(contract_id=contract_id).all()
    return jsonify([attachment.to_dict() for attachment in attachments])

@app.route('/api/contracts/<int:contract_id>/attachments', methods=['POST'])
def upload_attachment(contract_id):
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400
    
    # 检查合同是否存在
    contract = Contract.query.get_or_404(contract_id)
    
    # 获取附件描述
    description = request.form.get('description', '')
    
    # 获取文件类型
    filetype = file.content_type or mimetypes.guess_type(file.filename)[0] or 'application/octet-stream'
    
    # 创建附件记录
    attachment = ContractAttachment(
        contract_id=contract_id,
        filename=file.filename,
        filesize=0,  # 暂时设置为0，稍后更新
        filetype=filetype,
        description=description,
        filepath='',  # 暂时为空，稍后更新
        uploader='当前用户'  # 这里可以替换为实际的用户名
    )
    
    # 先添加记录获取ID
    db.session.add(attachment)
    db.session.flush()
    
    # 使用获取的ID生成文件路径
    filepath = ContractAttachment.get_path(attachment, file.filename)
    attachment.filepath = filepath
    
    # 确保上传目录存在
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    
    # 保存文件
    file.save(filepath)
    
    # 更新文件大小
    attachment.filesize = os.path.getsize(filepath)
    
    # 提交更改
    db.session.commit()
    
    return jsonify(attachment.to_dict()), 201

@app.route('/api/contracts/<int:contract_id>/attachments/<int:id>', methods=['DELETE'])
def delete_attachment(contract_id, id):
    attachment = ContractAttachment.query.filter_by(id=id, contract_id=contract_id).first_or_404()
    
    # 删除文件
    if os.path.exists(attachment.filepath):
        os.remove(attachment.filepath)
    
    # 删除记录
    db.session.delete(attachment)
    db.session.commit()
    
    return jsonify({'message': 'Attachment deleted successfully'})

# 附件下载API
@app.route('/api/attachments/download/<int:id>', methods=['GET'])
def download_attachment(id):
    # 尝试获取合同附件
    attachment = ContractAttachment.query.get(id)
    if not attachment:
        # 如果不是合同附件，尝试获取简历附件
        attachment = ResumeAttachment.query.get(id)
    if not attachment:
        # 如果不是简历附件，尝试获取证书附件
        attachment = CertificateAttachment.query.get_or_404(id)
    
    # 检查文件是否存在
    if not os.path.exists(attachment.filepath):
        return jsonify({'error': 'File not found'}), 404
    
    # 发送文件
    return send_file(
        attachment.filepath,
        mimetype=attachment.filetype,
        as_attachment=True,
        download_name=attachment.filename
    )

# 附件信息获取API
@app.route('/api/attachments/<int:id>', methods=['GET'])
def get_attachment(id):
    # 尝试获取合同附件
    attachment = ContractAttachment.query.get(id)
    if not attachment:
        # 如果不是合同附件，尝试获取简历附件
        attachment = ResumeAttachment.query.get_or_404(id)
    return jsonify(attachment.to_dict())

# 简历附件相关API
@app.route('/api/employees/<int:employee_id>/attachments', methods=['GET'])
def get_resume_attachments(employee_id):
    attachments = ResumeAttachment.query.filter_by(employee_id=employee_id).all()
    return jsonify([attachment.to_dict() for attachment in attachments])

@app.route('/api/employees/<int:employee_id>/attachments', methods=['POST'])
def upload_resume_attachment(employee_id):
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400
    
    # 检查员工是否存在
    employee = Employee.query.get_or_404(employee_id)
    
    # 获取附件描述
    description = request.form.get('description', '')
    
    # 获取文件类型
    filetype = file.content_type or mimetypes.guess_type(file.filename)[0] or 'application/octet-stream'
    
    # 创建附件记录
    attachment = ResumeAttachment(
        employee_id=employee_id,
        filename=file.filename,
        filesize=0,  # 暂时设置为0，稍后更新
        filetype=filetype,
        description=description,
        filepath='',  # 暂时为空，稍后更新
        uploader='当前用户'  # 这里可以替换为实际的用户名
    )
    
    # 先添加记录获取ID
    db.session.add(attachment)
    db.session.flush()
    
    # 使用获取的ID生成文件路径
    filepath = ResumeAttachment.get_path(attachment, file.filename)
    attachment.filepath = filepath
    
    # 确保上传目录存在
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    
    # 保存文件
    file.save(filepath)
    
    # 更新文件大小
    attachment.filesize = os.path.getsize(filepath)
    
    # 提交更改
    db.session.commit()
    
    return jsonify(attachment.to_dict()), 201

@app.route('/api/employees/<int:employee_id>/attachments/<int:id>', methods=['DELETE'])
def delete_resume_attachment(employee_id, id):
    attachment = ResumeAttachment.query.filter_by(id=id, employee_id=employee_id).first_or_404()
    
    # 删除文件
    if os.path.exists(attachment.filepath):
        os.remove(attachment.filepath)
    
    # 删除记录
    db.session.delete(attachment)
    db.session.commit()
    
    return jsonify({'message': 'Attachment deleted successfully'})

# 证书管理相关API
@app.route('/api/certificates', methods=['GET'])
def get_all_certificates():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    employee_id = request.args.get('employee_id', type=int)
    employee_name = request.args.get('employee_name', type=str)
    
    query = Certificate.query.join(Employee)  # 关联员工表
    
    if employee_id:
        query = query.filter(Certificate.employee_id == employee_id)
    if employee_name:
        query = query.filter(Employee.name.like(f'%{employee_name}%'))
    
    pagination = query.order_by(Certificate.created_at.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    return jsonify({
        'items': [item.to_dict() for item in pagination.items],
        'total': pagination.total,
        'pages': pagination.pages,
        'current_page': pagination.page
    })

@app.route('/api/certificates/<int:id>', methods=['GET'])
def get_certificate_detail(id):
    certificate = Certificate.query.get_or_404(id)
    return jsonify(certificate.to_dict())

@app.route('/api/certificates', methods=['POST'])
def create_certificate_record():
    data = request.get_json()
    
    certificate = Certificate(
        employee_id=data['employee_id'],
        name=data['name'],
        certificate_no=data['certificate_no'],
        level=data.get('level'),
        issuing_org=data['issuing_org'],
        issue_date=datetime.strptime(data['issue_date'], '%Y-%m-%d').date(),
        expiry_date=datetime.strptime(data['expiry_date'], '%Y-%m-%d').date() if data.get('expiry_date') else None,
        description=data.get('description')
    )
    
    db.session.add(certificate)
    db.session.commit()
    
    return jsonify(certificate.to_dict()), 201

@app.route('/api/certificates/<int:id>', methods=['PUT'])
def update_certificate_record(id):
    certificate = Certificate.query.get_or_404(id)
    data = request.get_json()
    
    certificate.name = data['name']
    certificate.certificate_no = data['certificate_no']
    certificate.level = data.get('level')
    certificate.issuing_org = data['issuing_org']
    certificate.issue_date = datetime.strptime(data['issue_date'], '%Y-%m-%d').date()
    certificate.expiry_date = datetime.strptime(data['expiry_date'], '%Y-%m-%d').date() if data.get('expiry_date') else None
    certificate.description = data.get('description')
    
    db.session.commit()
    
    return jsonify(certificate.to_dict())

@app.route('/api/certificates/<int:id>', methods=['DELETE'])
def delete_certificate_record(id):
    certificate = Certificate.query.get_or_404(id)
    
    # 删除相关附件
    attachments = CertificateAttachment.query.filter_by(certificate_id=id).all()
    for attachment in attachments:
        if os.path.exists(attachment.filepath):
            os.remove(attachment.filepath)
        db.session.delete(attachment)
    
    db.session.delete(certificate)
    db.session.commit()
    
    return '', 204

# 证书附件相关API
@app.route('/api/certificates/<int:certificate_id>/attachments', methods=['GET'])
def get_certificate_attachments(certificate_id):
    attachments = CertificateAttachment.query.filter_by(certificate_id=certificate_id).all()
    return jsonify([item.to_dict() for item in attachments])

def custom_secure_filename(filename):
    # 只去除不安全的字符，保留中文、字母、数字、常见符号
    return re.sub(r'[<>:"/\\|?*]', '', filename)

@app.route('/api/certificates/<int:certificate_id>/attachments', methods=['POST'])
def add_certificate_attachment(certificate_id):
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    description = request.form.get('description', '')
    uploader = request.form.get('uploader', '系统')
    # 保存文件
    filename = custom_secure_filename(file.filename)
    filepath = CertificateAttachment.get_path(filename=filename)
    file.save(filepath)
    # 创建附件记录
    attachment = CertificateAttachment(
        certificate_id=certificate_id,
        filename=filename,
        filesize=os.path.getsize(filepath),
        filetype=file.content_type,
        description=description,
        filepath=filepath,
        uploader=uploader
    )
    db.session.add(attachment)
    db.session.commit()
    return jsonify(attachment.to_dict()), 201

@app.route('/api/certificates/<int:certificate_id>/attachments/<int:attachment_id>', methods=['DELETE'])
def delete_certificate_attachment(certificate_id, attachment_id):
    attachment = CertificateAttachment.query.filter_by(
        certificate_id=certificate_id,
        id=attachment_id
    ).first_or_404()
    
    if os.path.exists(attachment.filepath):
        os.remove(attachment.filepath)
    
    db.session.delete(attachment)
    db.session.commit()
    
    return '', 204

# 证书名称管理API
@app.route('/api/certificate-names', methods=['GET'])
def get_certificate_names():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    name = request.args.get('name', '', type=str)
    level = request.args.get('level', '', type=str)
    query = CertificateName.query.filter_by(is_deleted=False)
    if name:
        query = query.filter(CertificateName.name.like(f"%{name}%"))
    if level:
        query = query.filter(CertificateName.level == level)
    pagination = query.order_by(CertificateName.id.desc()).paginate(page=page, per_page=per_page, error_out=False)
    return jsonify({
        'total': pagination.total,
        'page': page,
        'per_page': per_page,
        'total_pages': pagination.pages,
        'data': [item.to_dict() for item in pagination.items]
    })

@app.route('/api/certificate-names/<int:id>', methods=['GET'])
def get_certificate_name_detail(id):
    item = CertificateName.query.filter_by(id=id, is_deleted=False).first_or_404()
    return jsonify(item.to_dict())

@app.route('/api/certificate-names', methods=['POST'])
def create_certificate_name():
    data = request.get_json()
    name = data.get('name')
    level = data.get('level')
    issuing_org = data.get('issuing_org')
    if not name or not level:
        return jsonify({'error': '证书名称和级别为必填项'}), 400
    item = CertificateName(name=name, level=level, issuing_org=issuing_org)
    db.session.add(item)
    db.session.commit()
    return jsonify({'message': '证书名称创建成功', 'id': item.id}), 201

@app.route('/api/certificate-names/<int:id>', methods=['PUT'])
def update_certificate_name(id):
    item = CertificateName.query.filter_by(id=id, is_deleted=False).first_or_404()
    data = request.get_json()
    name = data.get('name')
    level = data.get('level')
    issuing_org = data.get('issuing_org')
    if name:
        item.name = name
    if level:
        item.level = level
    if issuing_org is not None:
        item.issuing_org = issuing_org
    db.session.commit()
    return jsonify({'message': '证书名称更新成功'})

@app.route('/api/certificate-names/<int:id>', methods=['DELETE'])
def delete_certificate_name(id):
    item = CertificateName.query.filter_by(id=id, is_deleted=False).first_or_404()
    item.is_deleted = True
    db.session.commit()
    return jsonify({'message': '证书名称已删除'})

@app.route('/api/employees/<int:employee_id>/contracts', methods=['GET'])
def get_employee_contracts(employee_id):
    """获取指定员工的合同列表"""
    contracts = Contract.query.filter_by(employee_id=employee_id).order_by(Contract.start_date.desc()).all()
    result = []
    for contract in contracts:
        contract_dict = contract.to_dict()
        # 增加员工姓名和电话，保持与合同管理一致
        contract_dict['employee_name'] = contract.employee.name if contract.employee else ''
        contract_dict['phone'] = contract.employee.phone if contract.employee else ''
        result.append(contract_dict)
    return jsonify(result)

# 档案附件相关API
@app.route('/api/archives/<int:archive_id>/attachments', methods=['POST'])
def upload_archive_attachment(archive_id):
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400
    
    # 检查档案是否存在（假设有Archive模型）
    # archive = Archive.query.get_or_404(archive_id)
    # 如无Archive模型，可跳过此步

    # 获取附件描述
    description = request.form.get('description', '')
    uploader = request.form.get('uploader', '系统')

    # 获取文件类型
    filetype = file.content_type or mimetypes.guess_type(file.filename)[0] or 'application/octet-stream'

    # 生成保存路径
    upload_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads', 'archives')
    os.makedirs(upload_dir, exist_ok=True)
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    filename = f"{archive_id}_{timestamp}_{file.filename}"
    filepath = os.path.join(upload_dir, filename)
    file.save(filepath)

    # 写入数据库（如有ArchiveAttachment模型）
    # attachment = ArchiveAttachment(
    #     archive_id=archive_id,
    #     filename=file.filename,
    #     filesize=os.path.getsize(filepath),
    #     filetype=filetype,
    #     description=description,
    #     filepath=filepath,
    #     uploader=uploader
    # )
    # db.session.add(attachment)
    # db.session.commit()
    # return jsonify(attachment.to_dict()), 201

    # 如无模型，返回简单信息
    return jsonify({
        'archive_id': archive_id,
        'filename': file.filename,
        'filesize': os.path.getsize(filepath),
        'filetype': filetype,
        'description': description,
        'filepath': filepath,
        'uploader': uploader
    }), 201

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000) 